﻿using System;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;
using RayDen.Library.Entity.Scene;
using RayDen.RayEngine.Core.Interface;
using RayDen.RayEngine.Core.Types;
using RayDen.RayEngine.Core.Types.Volume;

namespace RayDen.RayEngine.Engines.PathTracer
{
    // ReSharper disable RedundantThisQualifier

    public enum PathTracerPathState
    {
        EyeVertex,
        EyeVolume,
        NextVertex,
        ShadowRaysOnly
    }

    public class VolumePathTracerPath : PathSamplerBase
    {
        internal RgbSpectrum Throughput;
        public PathTracerPathState PathState;

        protected int depth, tracedShadowRayCount;
        public int rayID;
        protected float pathWeight;
        protected bool specularBounce;
        protected VolumeComputation volumeComp;
        protected RayHit eyeHit;

        protected RayEngineScene scene;

        public int MaxRaysPerPath
        {
            get;
            set;
        }

        struct ShadowRayInfo
        {
            public float pdf;
            public RgbSpectrum color;
            public RayData shadowRay;
            public int currentShadowRayIndex;
        }
        private ShadowRayInfo[] secRays;
        private SurfaceIntersectionData _hitInfo;


        public override void InitPath(IPathProcessor buffer)
        {
            base.InitPath(buffer);
            this.scene = pathIntegrator.Scene;
            this.Radiance = new RgbSpectrum(0f);
            this.Throughput = new RgbSpectrum(1f);
            this.PathState = PathTracerPathState.EyeVertex;
            if (this.secRays == null)
                this.secRays = new ShadowRayInfo[scene.ShadowRayCount];
            if (this.volumeComp == null)
            {
                this.volumeComp = scene.GetVolumeComputation();
            }
            else
            {
                this.volumeComp.Reset();
            }
            this.Sample = pathIntegrator.Sampler.GetSample(null);
            IRay ray;
            pathIntegrator.Scene.Camera.GetRay(Sample.imageX, Sample.imageY, out ray);
            this.PathRay = (RayData)ray;
            this.RayIndex = -1;
            this.pathWeight = 1.0f;
            this.tracedShadowRayCount = 0;
            this.depth = 0;
            this.specularBounce = true;
            this.rayID = (int)(Sample.imageX + Sample.imageY * 640f);
        }

        public override bool FillRayBuffer(RayBuffer rayBuffer)
        {
            var leftSpace = rayBuffer.LeftSpace();
            if (((PathState == PathTracerPathState.EyeVertex) && (1 > leftSpace)) ||
            ((PathState == PathTracerPathState.EyeVolume) && (volumeComp.GetRayCount() + 1 > leftSpace)) ||
            ((PathState == PathTracerPathState.ShadowRaysOnly) && (tracedShadowRayCount > leftSpace)) ||
            ((PathState == PathTracerPathState.NextVertex) && (tracedShadowRayCount + 1 > leftSpace)))
                return false;
            if (PathState == PathTracerPathState.EyeVolume)
            {
                volumeComp.AddRays(rayBuffer);
                return true;
            }
            if (PathState != PathTracerPathState.ShadowRaysOnly)
                RayIndex = rayBuffer.AddRay(ref PathRay);
            if (PathState == PathTracerPathState.NextVertex || PathState == PathTracerPathState.ShadowRaysOnly)
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                    secRays[i].currentShadowRayIndex = rayBuffer.AddRay(ref secRays[i].shadowRay);
            }
            return true;
        }


        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
#if VERBOSE
            try
            {
#endif
                base.Advance(rayBuffer, consumer);



                var rayHit = new RayHit();

                Vector wo = -PathRay.Dir;

                switch (PathState)
                {
                    case PathTracerPathState.EyeVertex:
                        float t, t1;
                        if (scene.VolumeIntegrator != null && scene.VolumeIntegrator.GetBounds().Intersect(PathRay, out t, out t1))
                        {
                            rayHit = rayBuffer.rayHits[RayIndex];

                            // Use Russian Roulette to check if I have to do participating media computation or not
                            if (Sample.GetLazyValue() <= scene.VolumeIntegrator.GetRRProbability())
                            {
                                RayData volumeRay = new RayData(ref PathRay.Org, ref PathRay.Dir, 0f,
                                                                rayHit.Miss() ? 1e10f : rayHit.Distance);
                                scene.VolumeIntegrator.GenerateLiRays(scene, Sample, ref volumeRay, volumeComp);
                                Radiance += volumeComp.GetEmittedLight();

                                if (volumeComp.GetRayCount() > 0)
                                {
                                    // Do the EYE_VERTEX_VOLUME_STEP
                                    PathState = PathTracerPathState.EyeVolume;
                                    eyeHit = (rayBuffer.rayHits[RayIndex]);
                                    return;
                                }
                            }
                        }
                        else
                        {
                            rayHit = rayBuffer.rayHits[RayIndex];
                        }
                        break;
                    case PathTracerPathState.NextVertex:
                        rayHit = rayBuffer.rayHits[RayIndex];
                        break;
                    case PathTracerPathState.EyeVolume:
                        Radiance += Throughput * volumeComp.CollectResults(rayBuffer) /
                                    scene.VolumeIntegrator.GetRRProbability();
                        rayHit = eyeHit;
                        break;
                }

                if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                    (tracedShadowRayCount > 0))
                {
                    for (int i = 0; i < tracedShadowRayCount; ++i)
                    {
                        RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].currentShadowRayIndex];
                        RgbSpectrum attenuation;
                        if (this.ShadowRayTest(ref shadowRayHit, out attenuation))
                        {
                            //                            Radiance.MADD()
                            Radiance += attenuation * ((secRays[i].color) / secRays[i].pdf);
                            pathWeight *= secRays[i].pdf;
                        }
                    }
                    tracedShadowRayCount = 0;
                    if (PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
                    {
                        Splat(consumer);
                        return;
                    }
                }

                depth++;
                bool missed = rayHit.Index == 0xffffffffu;
                if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
                {
                    if (specularBounce && missed)
                    {
                        Radiance += this.SampleEnvironment(-PathRay.Dir) * Throughput;
                    }
                    Splat(consumer);
                    return;
                }

                // Something was hit
                if (_hitInfo == null)
                    _hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit);
                else
                {
                    SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref _hitInfo);
                }
                var currentTriangleIndex = (int)rayHit.Index;

                //If Hit light)
                if (_hitInfo.IsLight)
                {
                    if (specularBounce)
                    {
                        var lt = scene.GetLightByIndex(currentTriangleIndex);
                        if (lt == null)
                        {
                            goto errro;
                        }
                        var le = (RgbSpectrum)(RgbSpectrumInfo)(lt.Le(ref wo));
                        Radiance += Throughput * le;
                    }
                    Splat(consumer);
                    return;
                }
            @errro:

                var hitPoint = PathRay.Point(rayHit.Distance);

                tracedShadowRayCount = 0;
                if (_hitInfo.MMaterial.IsDiffuse())
                {
                    float lightStrategyPdf = scene.ShadowRayCount / (float)scene.Lights.Length;
                    RgbSpectrum lightTroughtput = Throughput * _hitInfo.Color;
                    for (int i = 0; i < scene.ShadowRaysPerSample; ++i)
                    {
                        int currentLightIndex = scene.SampleLights(Sample.GetLazyValue());
                        var light = scene.Lights[currentLightIndex];

                        var ls = new LightSample();
                        light.EvaluateShadow(ref hitPoint, ref _hitInfo.ShadingNormal, Sample.GetLazyValue(),
                                             Sample.GetLazyValue(), Sample.GetLazyValue(), ref ls);
                        if (ls.Pdf <= 0f)
                        {
                            continue;
                        }

                        secRays[tracedShadowRayCount].color = ls.Spectrum.GetType() == typeof(RgbSpectrumInfo) ? (RgbSpectrum)(RgbSpectrumInfo)ls.Spectrum : (RgbSpectrum)ls.Spectrum;
                        secRays[tracedShadowRayCount].pdf = ls.Pdf;
                        secRays[tracedShadowRayCount].shadowRay = ls.LightRay;

                        RgbSpectrum fs;
                        _hitInfo.MMaterial.f(
                            ref secRays[tracedShadowRayCount].shadowRay.Dir,
                            ref wo, ref _hitInfo.ShadingNormal, ref Throughput, out fs);
                        Vector lwi = secRays[tracedShadowRayCount].shadowRay.Dir;
                        secRays[tracedShadowRayCount].color *= lightTroughtput *
                                                               Vector.AbsDot(ref _hitInfo.ShadingNormal, ref lwi) *
                                                               fs;
                        if (!secRays[tracedShadowRayCount].color.IsBlack())
                        {
                            secRays[tracedShadowRayCount].pdf *= lightStrategyPdf;
                            tracedShadowRayCount++;
                        }
                    }
                }

                float fPdf;
                Vector wi;

                RgbSpectrum f = _hitInfo.MMaterial.Sample_f(ref wo, out wi, ref _hitInfo.Normal, ref _hitInfo.ShadingNormal, ref Throughput,
                                                          Sample.GetLazyValue(), Sample.GetLazyValue(),
                                                          Sample.GetLazyValue(), ref _hitInfo.TextureData,
                                                          out fPdf, out specularBounce);

                if ((fPdf <= 0.0f) || f.IsBlack())
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);
                    }
                    return;
                }
                pathWeight *= fPdf;
                Throughput *= f / fPdf;

                if (depth > scene.MaxPathDepth)
                {
                    float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                    if (prob >= Sample.GetLazyValue())
                    {
                        Throughput /= prob;
                        pathWeight *= prob;
                    }
                    else
                    {
                        if (tracedShadowRayCount > 0)
                            PathState = PathTracerPathState.ShadowRaysOnly;
                        else
                        {
                            Splat(consumer);
                        }

                        return;
                    }
                }

                PathRay.Org = hitPoint;
                PathRay.Dir = wi.Normalize();
                PathState = PathTracerPathState.NextVertex;

#if VERBOSE

            }
            catch (Exception ex)
            {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);
                throw;
            }
#endif
        }

        private bool ShadowRayTest(ref RayHit shadowRayHit, out RgbSpectrum attenuation)
        {
            var hit = shadowRayHit.Index == 0xffffffffu || scene.IsLight((int)shadowRayHit.Index);
            attenuation = new RgbSpectrum(1f);
            if (shadowRayHit.Distance > 0f)
            {
                attenuation *= MathLab.Exp(-(shadowRayHit.Distance));
            }
            else
            {
                attenuation *= MathLab.Exp(-(this.scene.SceneGeometry.BoundingSphereRadius * 0.1f));

            }
            if (hit) return true;
            var mesh = scene.GetMeshByTriangleIndex((int)shadowRayHit.Index);
            var mat =
                //SurfaceMaterials.CreateMaterial(scene.MaterialProvider.Get(mesh.MaterialName));
                scene.MatLib.GetSurfMat(mesh != null ? mesh.MaterialName : "default");

            if (mat.AlphaTexture != null)
            {
                attenuation = (RgbSpectrum) (mat.AlphaTexture as ConstTextureInfo).Color;
                hit = true;
                //mat.MaterialData.Kt.Filter() < Sample.GetLazyValue();
            }

            return hit;
        }

        private RgbSpectrum SampleEnvironment(Vector vector)
        {
            return this.scene.SampleEnvironment(vector);
        }
    }
    // ReSharper restore RedundantThisQualifier
}